import React, { useEffect, useState, useRef } from 'react'
import { Card, Col, Row, List, Avatar, Drawer } from 'antd';
import { PieChartOutlined } from '@ant-design/icons';
import axios from 'axios';
import * as echarts from 'echarts';
import _ from 'lodash'
const { Meta } = Card;


export default function Home() {
  const [viewList, setViewList] = useState([])
  const [starList, setStarList] = useState([])
  const barRef = useRef(null)
  const pieRef = useRef(null)
  const { username, region, role: { roleName } } = JSON.parse(localStorage.getItem('token'))
  const [open, setOpen] = useState(false);
  const [pieInit, setPieInit] = useState(null)
  const [allList, setAllList] = useState([])

  // 最多浏览数据
  useEffect(() => {
    axios.get("/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6").then(res => {
      // console.log(res)
      setViewList(res.data)
    })
  }, [])

  // 点赞最多数据
  useEffect(() => {
    axios.get("/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6").then(res => {
      // console.log(res)
      setStarList(res.data)
    })
  }, [])

  // 柱状图数据
  useEffect(() => {
    axios.get('/news?publishState=2&_expand=category').then(res => {
      // console.log(_.groupBy(res.data, item => item.category.title))
      renderBar(_.groupBy(res.data, item => item.category.title))
      setAllList(res.data)
    })
  }, [])

  // 初始化柱状图
  const renderBar = (item) => {
    var myChart = echarts.init(barRef.current);
    var option = {
      title: {
        text: '新闻分类展示'
      },
      tooltip: {},
      legend: {
        data: ['数量']
      },
      xAxis: {
        data: Object.keys(item)
      },
      yAxis: {},
      series: [
        {
          name: '数量',
          type: 'bar',
          data: Object.values(item).map(item => item.length)
        }
      ]
    };

    myChart.setOption(option);
  }

  // 饼状图
  const renderPie = () => {
    const currentList = allList.filter(item => item.author === username)
    const obj = _.groupBy(currentList, item => item.category.title)
    // console.log(obj)
    const list = []
    for (let i in obj) {
      list.push({
        name: i,
        value: obj[i].length
      })
    }
    var myChart
    if (!pieInit) {
      myChart = echarts.init(pieRef.current);
      setPieInit(myChart)
    } else {
      myChart = pieInit
    }
    var option;

    option = {
      title: {
        text: '个人新闻展示',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '新闻',
          type: 'pie',
          radius: '50%',
          data: list,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };

    option && myChart.setOption(option);
  }

  // 控制抽屉
  const showDrawer = () => {
    setOpen(true);
    setTimeout(() => {
      renderPie()
    }, 0)
  };
  const onClose = () => {
    setOpen(false);
  };

  return (
    <div>
      <Row gutter={16}>
        <Col span={8}>
          <Card title="用户最多浏览" bordered={false}>
            <List
              size="large"
              dataSource={viewList}
              renderItem={(item) => <List.Item><a href={`#/news-manage/preview/${item.id}`}>{item.title}</a></List.Item>}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card title="用户最多点赞" bordered={false}>
            <List
              size="large"
              dataSource={starList}
              renderItem={(item) => <List.Item><a href={`#/news-manage/preview/${item.id}`}>{item.title}</a></List.Item>}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card
            cover={
              <img
                alt="example"
                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
              />
            }
            actions={[
              <PieChartOutlined onClick={() => showDrawer()} />,
            ]}
          >
            <Meta
              avatar={<Avatar src="https://xsgames.co/randomusers/avatar.php?g=pixel" />}
              title={username}
              description={<div><span style={{ marginRight: '30px' }}>{region}</span><span>{roleName}</span></div>}
            />
          </Card>
        </Col>
      </Row>
      <div ref={barRef} style={{ height: '220px', marginTop: '20px' }}></div>

      <Drawer
        width={700}
        title="个人新闻"
        closable={true}
        onClose={onClose}
        open={open}
      >
        <div ref={pieRef} style={{ height: '600px' }}></div>
      </Drawer>
    </div>
  )
}
